#coding:utf-8
import json, hashlib, time
import urllib2
import xml.etree.ElementTree as ET
from django.core.cache import cache
from lovewith.share.views.modules.share import ShareApi
from lovewith.website.models import WeixinMp


class Weixin:
    def __init__(self):
        self.token = 'lovewith'
        self.shortcut = []
        self.shortcut_data = {}
        self.my_username = None

        cache_key = 'mt_weixin'
        #缓存时间(秒)
        cache_time = 5 * 60
        result = cache.get(cache_key)
        if result:
            self.shortcut = result.get('shortcut')
            self.shortcut_data = result.get('shortcutData')
        else:
            reply_filter_data = WeixinMp.objects.all().order_by('-id')
            if reply_filter_data.exists():
                try:
                    auto_reply_data = json.loads(reply_filter_data[0].content)
                    for data in auto_reply_data:
                        self.shortcut.append('%s:%s' % (data.get('key'), data.get('name')))
                        self.shortcut_data[data.get('key')] = data.get('news')

                    cache.set(cache_key, {'shortcut': self.shortcut, 'shortcutData': self.shortcut_data}, cache_time)
                except StandardError, api_error:
                    pass

    #判断dict是否为空
    @staticmethod
    def is_not_none(params):
        for k, v in params.items():
            if v is None:
                return False
        return True

    # XMl To JSON
    @staticmethod
    def to_json(xml_body):
        #http://docs.python.org/2/library/xml.etree.elementtree.html#xml.etree.ElementTree.XML
        json_data = {}
        root = ET.fromstring(xml_body)
        for child in root:
            if child.tag == 'CreateTime':
                value = long(child.text)
            else:
                value = child.text
            json_data[child.tag] = value

        return json_data

    #cdata
    @staticmethod
    def add_cdata(data):
        #http://stackoverflow.com/questions/174890/how-to-output-cdata-using-elementtree
        if type(data) is str or type(data) is unicode:
            return '<![CDATA[%s]]>' % data.replace(']]>', ']]]]><![CDATA[>')
        return data

    #JSON To XMl
    def to_xml(self, xml_data, wrap_tag=None):
        xml = ''
        if wrap_tag:
            xml = '<%s>' % wrap_tag

        for item in xml_data:
            tag = item.keys()[0]
            value = item.values()[0]
            xml += '<%s>%s</%s>' % (tag, self.add_cdata(value), tag)

        if wrap_tag:
            xml += '</%s>' % wrap_tag

        return xml

    #验证信息是否来自微信
    def validate(self, signature, timestamp, nonce, echostr):
        params = {'token': self.token, 'timestamp': timestamp, 'nonce': nonce}

        if self.is_not_none(params):
            sort_params = sorted([v for k, v in params.items()])
            client_signature = hashlib.sha1(''.join(sort_params)).hexdigest()

            if client_signature == signature:
                return echostr

        return False

    #回复文字信息
    def reply_text_msg(self, to_user, reply_msg):
        if to_user and reply_msg:
            response_msg = self.to_xml([
                                           {'ToUserName': to_user},
                                           {'FromUserName': self.my_username},
                                           {'CreateTime': int(time.time())},
                                           {'MsgType': 'text'},
                                           {'Content': reply_msg}
                                       ], 'xml')

            return response_msg

    #处理新闻
    def get_article(self, to_user, article_data):
        article_count = len(article_data)
        atricle_xml = '<xml>'

        base_xml_data = self.to_xml([
            {'ToUserName': to_user},
            {'FromUserName': self.my_username},
            {'CreateTime': int(time.time())},
            {'MsgType': 'news'},
            {'ArticleCount': article_count}
        ])

        atricle_xml += base_xml_data
        atricle_xml += '<Articles>'

        for atricle in article_data:
            item_xml = self.to_xml([
                                       {'Title': atricle.get('title')},
                                       {'Description': atricle.get('description')},
                                       {'PicUrl': atricle.get('picurl')},
                                       {'Url': atricle.get('url')}
                                   ], 'item')

            atricle_xml += item_xml

        atricle_xml += '</Articles>'
        atricle_xml += '</xml>'

        return atricle_xml

    #处理接收到的微信信息
    def get_message(self, xml_body):
        json_data = self.to_json(xml_body)
        user = json_data.get('FromUserName')
        msg = json_data.get('Content')
        msg_type = json_data.get('MsgType')
        event = json_data.get('Event' or None)

        self.my_username = json_data.get('ToUserName')

        if msg_type == 'event' and event == 'subscribe':
            #添加订阅
            #self.addSubscribe(json_data)

            #回复订阅成功
            reply_msg = '/::$亲，终于等到您来了！感谢关注婚礼时光，我们会每日分享图文并茂的婚礼资讯或婚礼灵感，' \
                        '给热爱婚礼和正在筹备婚礼的亲们。婚礼时光创意社区：http://www.lovewith.me/，电子请柬上线啦，' \
                        '您可以定制和发送请柬给亲友哦！现在直接回复关于婚礼的“任意搜索词”，' \
                        '例如“手捧花”“婚纱”等，就能立即收到相关婚礼灵感！回复“1”查看最新婚礼相关内容，' \
                        '回复“2”进入新娘SHOP选购最美婚纱婚品等' \
                        '，回复“3”查看婚礼类目和热门标签进行精准搜索，回复“4”查看最实用的新娘百科问答！' \
                        '看到您喜欢的内容，记得收藏和转发到朋友圈哦~/:,@-D'

            return self.reply_text_msg(user, reply_msg)

        if msg_type == 'text':
            article_data = self.shortcut_data.get(msg)

            if article_data:
                return self.get_article(user, article_data)
            else:
                #根据用户输入的关键词获取搜索结果
                atricle_share_data = []
                share_search_data = ShareApi.get_by_title(msg, page_no=1)
                share_data = share_search_data['share'][:4]
                if share_data:
                    #问答搜索结果
                    ask_url = 'http://ask.lovewith.me/index.php?qa=api&qa_1=search&qa_2=%s' % msg
                    ask_data = json.loads(urllib2.urlopen(ask_url).read())

                    if ask_data:
                        share_data.extend(ask_data[:3])
                    #帖子搜索结果
                    for data in share_data:
                        cover = ''
                        if 'cover' in data:
                            cover = data['cover']
                            if cover.find('http') > -1:
                                cover = '%s!240' % cover
                            else:
                                #2012/09/05/ee31c3ca628bab3d0d4cfdcd6780abec8UBbf9_650x999.jpg
                                cover = 'http://img.lovewith.me/static/upload/%s' % cover

                        if 'link' in data:
                            url = data['link']
                        else:
                            url = 'http://www.lovewith.me/share/detail/all/%s/' % data['share_id']

                        atricle_share_data.append({
                            'title': data['title'],
                            'description': data['description'][0:25],
                            'picurl': cover,
                            'url': url
                        })
                    '''
                    atricle_share_data.append({
                        'title': u'更多%s' % total_count,
                        'description': '',
                        'picurl': '',
                        'url': ''
                    })
                    '''

                    return self.get_article(user, atricle_share_data)

                else:
                    reply_text = '没有找到对应信息'
                    return self.reply_text_msg(user, reply_text)